package bairui.international.weixin.portal.miniapp.controller.login;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lianjing.sh.spring.web.controller.enhance.annotation.FormatRestController;
import com.lianjing.sh.spring.web.controller.enhance.output.FomatOutput;
import com.lianjing.sh.wx.mp.miniapp.tool.Util_WxAppLogin;
import com.lianjing.sh.wx.mp.miniapp.tool.Util_WxAppLogin.Model_UserInfoData;

import bairui.international.common.config.Config_Path;
import bairui.international.common.tool.Util_GenerateQRCode;
import bairui.international.model.domain.jpa.TB_User;
import bairui.international.model.status.State_User;
import bairui.international.model.type.Type_User;
import bairui.international.service.Service_User;
import bairui.international.weixin.portal.miniapp.config.Config_Weixin_App;
import lombok.AllArgsConstructor;
import lombok.Getter;


/**
 * @generated
 *
 * @see Test_C_Login_Login 测试
 *
 */
//@FormatRestController
@Controller
public class C_Login_Login {
	
	@Autowired private Config_Weixin_App config_Weixin_App;
	@Autowired private Service_User service_User;
	@Autowired private Config_Path config_Path;
	
//	@ResponseStatus(HttpStatus.CREATED)
	@PostMapping(value="/wx/login", consumes=MediaType.APPLICATION_JSON_VALUE)
	public @ResponseBody @FomatOutput Object login(
		HttpServletRequest request,
		@Valid @RequestBody Util_WxAppLogin.GainUserInfoInput input,
		BindingResult bindingResult
	) throws Exception {
		// 后台校验
		if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            String validMess = fieldError.getDefaultMessage();
            System.out.println(fieldError.getField() + "======" + validMess);
//            model.addAttribute("errors", validMess);
            return "error";
        }
		Model_UserInfoData userInfo = Util_WxAppLogin.gainUserInfo(config_Weixin_App, input);
		// 保存或更新数据
		TB_User user = service_User.findOne(it->it.openid.eq(userInfo.getCode2session().getOpenid()));
		if(null == user){
			String avatarUrl = userInfo.getUserInfo().getAvatarUrl();
			user = service_User.save(userInfo, new TB_User());
			// 创建二维码
			String fileName = Util_GenerateQRCode.generateQRCode(config_Path.getPosition_Image_QR_CompanyStaff(), "user", String.valueOf(user.getId()), avatarUrl);
	    	service_User.setDimensionalUrl(user.getId(), fileName);
		} else {
			/*
			 * 冻结处理
			 */
			if(user.getState() == State_User.Freezed){
				return new Output_Login(user.getSkey(), Output_Login.State.Invalid, "用户已经冻结", new Output_User(
						user.getId(), 
						user.getNickName(),
						user.getType()
					));
//				throw new ValidateObjectException("object", "", "用户已经冻结");
			}
			/*
			 * 更新数据
			 */
			user = service_User.update(user.getId(), userInfo);
		}
		//
		return new Output_Login(user.getSkey(), Output_Login.State.OK, null, new Output_User(
				user.getId(), 
				user.getNickName(),
				user.getType()
			));
	}
	
	@GetMapping(value="/wx/islogin", consumes=MediaType.APPLICATION_JSON_VALUE)
	public @ResponseBody @FomatOutput Object isLogin(@RequestParam(required=false) String skey){
		if(null == skey){
			return new Output_Login(null, Output_Login.State.Invalid, null, null);
		}
		TB_User user = service_User.findOne(it->it.skey.eq(skey));
		if(null == user){
			return new Output_Login(null, Output_Login.State.Invalid, null, null);
		}
		return new Output_Login(user.getSkey(), Output_Login.State.OK, null, new Output_User(
				user.getId(), 
				user.getNickName(),
				user.getType()
			));
	}
	
	@AllArgsConstructor
	public static class Output_Login {
		
		public enum State {
			OK, Invalid
		}
		
		@Getter private String skey;
		@Getter private State state;
		@Getter private String message;
		@Getter private Output_User user;
	}
	
	@AllArgsConstructor
	public static class Output_User {
		@Getter private Long id;
		@Getter private String nickName;
		@Getter private Type_User type;
	}
	
}